<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('关联项目')" prop="dealId">
            <el-select v-model="form.dealId" filterable :disabled="($route.query.id !== undefined && $route.query.id !== null && $route.query.id !== '') || (form.id !== undefined && form.id !== null && form.id !== '') || (form.dealId !== undefined && form.dealId !== null && form.dealId !== '')" :placeholder="$t('关联项目')" @change="changeDeal">
              <el-option
                v-for="dict in dealListOption"
                :key="dict.id"
                :label="$t(dict.dealName)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('父级任务')" prop="parentId">
            <el-select v-model="form.parentId" :disabled="form.id !== undefined && form.id !== null && form.id !== ''" :placeholder="$t('父级任务')">
              <el-option :label="$t('无')" value="0" />
              <el-option
                v-for="dict in parentOptions"
                :key="dict.id"
                :label="$t(dict.itemName)"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项名称')" prop="itemName">
            <el-input v-model="form.itemName" :placeholder="$t('事项名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项负责人')" prop="personCharge">
            <UserSelect v-model="form.personCharge" :multiple="true" :placeholder="$t('事项负责人')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('事项参与人')" prop="participants">
            <el-input v-model="form.participants" :placeholder="$t('事项参与人')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('完成后跳转阶段')" prop="verificationPhase">
            <el-select v-model="form.verificationPhase" :placeholder="$t('完成后跳转阶段')">
              <el-option
                v-for="node in wordFlowNodeList"
                :key="node.nodeId"
                :label="$t(node.wfConfigNode.nodeName)"
                :value="node.nodeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计开始时间')" prop="estimatedStartTime">
            <el-date-picker
              v-model="form.estimatedStartTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('预计开始时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计完成时间')" prop="completionTime">
            <el-date-picker
              v-model="form.completionTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('预计完成时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" prop="complete">
          <el-form-item :label="$t('是否完成')">
            <el-radio-group v-model="form.complete" @change="completeChange">
              <el-radio
                v-for="dict in completeOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ dict.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.complete === 'Y'" :span="12">
          <el-form-item :label="$t('实际完成时间')" prop="actualTime">
            <el-date-picker
              v-model="form.actualTime"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('实际完成时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒人')" prop="remindUser">
            <UserSelect
              v-model="form.remindUser"
              :multiple="true"
              fund-invest
              :placeholder="$t('提醒人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
            <el-radio-group v-model="form.reminderFrequency">
              <el-radio
                v-for="dict in reminderFrequencyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.reminderFrequency === 'TIMER'" :span="12">
          <el-form-item :label="$t('定时提醒时间')" prop="remindTime">
            <el-date-picker
              v-model="form.remindTime"
              clearable
              style="width: 200px"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm"
              :placeholder="$t('定时提醒时间')"
            />
          </el-form-item>
        </el-col>
        <el-col v-else :span="24">
          <el-form-item :label="$t('频率提醒表达式')" prop="cron">
            <Cron v-model="form.cron" :cron-value.sync="form.frequencyCronValue" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('提醒状态')" prop="status">
            <el-switch
              v-model="form.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-text="$t('开启')"
              :inactive-text="$t('关闭')"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关联退出计划事项')" prop="exitPlanItem">
            <dict-select
              v-model="form.exitPlanItem"
              dictionary="exit_plan_item"
              :placeholder="$t('关联退出计划事项')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('情况说明')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('情况说明')" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable has-permi="deal:supervise" :list.sync="form.fileList" data-type="deal_supervise" :business-id="form.dealId" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <!--      <FormBtn ref="formBtn" :bus-data="form" has-permi="deal:supervise" :menu-key="menuKey" />-->
      <SaveBtn has-permi="deal:supervise" />
    </div>
  </div>
</template>

<script>
import {
  saveDealSupervise,
  getDealSupervise,
  findListSupervise,
  checkCommitNextNodeByBusId
} from '@/api/sass/kaihui/supervise/kaiHuiSupervise'
import { findDeal, getDealName } from '@/api/base/deal/dealBase'
import { getParentNode } from '@/api/act/busFlow/wfBusNode'
import Cron from '@/components/Cron'
export default {
  components: {
    Cron
  },
  data() {
    // 校验时间 预计开始时间   estimatedStartTime
    const checkTimeYJ = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback(new Error(this.$t('必填信息')))
      } else {
        if (this.form.estimatedStartTime !== undefined && this.form.estimatedStartTime !== null && this.form.completionTime !== undefined && this.form.completionTime !== null) {
          if (new Date(this.form.estimatedStartTime).getTime() > new Date(this.form.completionTime).getTime()) {
            callback(new Error(this.$t('不能晚于预计完成时间')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    // 校验时间 预计开始时间 estimatedStartTime   实际完成时间 actualTime
    const checkTimeWC = (rule, value, callback) => {
      if (value === undefined || value === null || value === '') {
        callback(new Error(this.$t('必填信息')))
      } else {
        if (this.form.estimatedStartTime !== undefined && this.form.estimatedStartTime !== null && this.form.actualTime !== undefined && this.form.actualTime !== null) {
          if (new Date(this.form.estimatedStartTime).getTime() > new Date(this.form.actualTime).getTime()) {
            callback(new Error(this.$t('不能早于预计开始时间')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    return {
      // 菜单标识
      menuKey: 'deal_supervise',
      // 表单参数
      form: {
        fileList: []
      },
      // 表单校验
      rules: {
        dealId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        itemName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        parentId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        personCharge: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        participants: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        complete: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        estimatedStartTime: [{ required: true, validator: checkTimeYJ, trigger: 'blur' }],
        completionTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        actualTime: [{ required: true, validator: checkTimeWC, trigger: 'blur' }]
      },
      // 是否隐藏其它按钮
      otherBtnHide: false,
      // 流程一级节点
      wordFlowNodeList: [],
      // 退出计划事项options
      exitPlanItemOptions: [],
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      completeOptions: [],
      dealListOption: [],
      parentOptions: [],
      reminderFrequencyOptions: []
    }
  },
  created() {
    this.getDicts('sys_yes_no').then(response => {
      this.completeOptions = response.data
    })
    this.getDicts('exit_plan_item').then(response => {
      this.exitPlanItemOptions = response.data
    })
    findDeal().then(response => {
      this.dealListOption = response.data
    })
    this.getDicts('reminder_frequency').then(response => {
      this.reminderFrequencyOptions = response.data
    })
    this.$bus.$emit('async_done')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      this.parentOptions = []
      if (data != null && data.id !== undefined) {
        getDealSupervise(data.id).then(response => {
          this.form = response.data
          this.getParentSelect(this.form.dealId)
          this.getWorkFlowNode()
          this.loading = false
        })
      } else {
        this.reset()
        if (this.$route.query.id) {
          this.getParentSelect(this.$route.query.id)
          this.getWorkFlowNode()
        }
        this.loading = false
      }
    },
    ganttInit(data) {
      this.loading = true
      this.parentOptions = []
      if (data != null && data.id !== undefined) {
        getDealSupervise(data.id).then(response => {
          this.form = response.data
          this.getParentSelect(this.form.dealId)
          this.getWorkFlowNode()
          this.loading = false
        })
      } else {
        this.reset()
        this.form.dealId = data.dealId
        this.form.parentId = data.rowId
        this.getParentSelect(this.form.dealId)
        this.getWorkFlowNode()
        this.loading = false
      }
    },
    getParentSelect(dealId) {
      findListSupervise({ dealId: dealId, parentId: '0' }).then(response => {
        this.parentOptions = response.rows
        console.log(this.parentOptions)
      })
    },
    changeDeal(val) {
      // 加载父级下拉
      this.form.parentId = '0'
      this.getParentSelect(val)
      this.getWorkFlowNode()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dealId: this.$route.query.id,
        parentId: undefined,
        itemName: undefined,
        personCharge: [],
        participants: undefined,
        verificationPhase: undefined,
        complete: 'N',
        estimatedStartTime: undefined,
        completionTime: undefined,
        actualTime: undefined,
        remark: undefined,
        actId: undefined,
        exitPlanItem: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        fileList: [],
        remindUserId: [],
        reminderFrequency: 'TIMER',
        status: 1
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      if (this.$parent.$parent.reset !== undefined) {
        this.$parent.$parent.reset()
      }
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      this.$refs['form'].validate(valid => {
        // 验证数据
        if (valid) {
          // 弹出遮罩层
          checkCommitNextNodeByBusId(this.form).then(response => {
            if (response.data === 'block') {
              var fromData = this.form
              var currentThis = this
              this.$confirm(this.$t('保存后项目阶段不会发生变化,原因:[' + response.datas.notThroughNode + ']尚未完成审批'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return currentThis.saveData(fromData, type)
                })
                .catch(function() {
                })
            } else {
              this.saveData(this.form, type)
            }
          })
        } else {
          this.locationError(document)
        }
      })
    },
    saveData(data, type) {
      // 保存数据
      this.loading = true
      saveDealSupervise(data).then(response => {
        if (response.code === 200) {
          // 点击的按钮是保存并启动流程
          if (type === 'process') {
            // 启动流程
            this.startProcess(response.data.id)
            // 点击的仅保存
          } else {
            this.msgSuccess(this.$t('保存成功'))
            // 关闭form页面
            this.closeForm()
          }
          this.$emit('submitFormEnd', null)
        } else {
          this.msgError(response.msg)
          this.loading = false
        }
      })
    },
    getWorkFlowNode() {
      getParentNode('deal', this.form.dealId).then(response => {
        console.log(response)
        this.wordFlowNodeList = response.data
      })
    },

    // 启动流程
    startProcess: async function(dataId) {
      var dealName = await getDealName(this.form.dealId)
      this.loading = false
      // 启动流程时候传入的参数.
      const processData = {}
      // 待办标题
      processData.title = '「' + dealName + '」' + ':' + this.form.itemName
      // 业务表名
      processData.dataTable = 'deal_supervise'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/saas/kaihui/supervise/kaiHuiSuperviseForm'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    completeChange() {
      if (this.form.complete === 'N') {
        this.form.actualTime = undefined
      }
    }
  }

}
</script>
